//
//  NewLoginView.m
//  mendianjieke
//
//  Created by 响当当 on 11/15/19.
//  Copyright © 2019 dongzheng. All rights reserved.
//

#import "NewLoginView.h"
#import "DemoView.h"
#import "BussinessView.h"
#import "HWTabBarController.h"
#import "LoginFailedView.h"

@interface NewLoginView ()
@property (nonatomic, strong)UILabel *titleLabel;//欢迎登录导购天眼
@property (nonatomic, strong)UIButton *demoButton;//演示demo
@property (nonatomic, strong)UIView *demoLineView;//演示demo下划线
@property (nonatomic, strong)UIButton *businessButton;//企业
@property (nonatomic, strong)UIView *businessLineView;//企业下划线

@property (nonatomic, strong)DemoView *demoView;
@property (nonatomic, strong)BussinessView *bussinessView;

@property (nonatomic, strong)NSString *phoneNum;//手机号码
@property (nonatomic, strong)NSString *phoneCipher;//手机密码
@property (nonatomic, strong)NSString *phoneCode;//手机验证码
@property (nonatomic, strong)NSString *phoneDemoCode;//手机demo验证码
@property (nonatomic, strong)NSString *type;
@property (nonatomic, assign)NSInteger segmentNum;//

@property (nonatomic, strong)HWTabBarController *vc;
@property (nonatomic, strong)LoginFailedView *loginFailedView;//提示

@end

@implementation NewLoginView

- (HWTabBarController *)vc
{
    if (!_vc)
    {
        _vc = [[HWTabBarController alloc]init];
    }
    return _vc;
}

- (LoginFailedView *)loginFailedView
{
    if (!_loginFailedView)
    {
        _loginFailedView = [[LoginFailedView alloc]initWithFrame:CGRectMake(0,0,SCREEN_WIDTH,SCREEN_HEIGHT)];
    }
    return _loginFailedView;
}

- (UILabel *)titleLabel
{
    if (!_titleLabel)
    {
        _titleLabel = [Utilties creatLabelWithFrame:CGRectMake(15*kUIScaleBasePlus,30*kUIScaleBasePlus,300*kUIScaleBasePlus,35*kUIScaleBasePlus)
                                               textAligment:NSTextAlignmentLeft
                                                   textClor:LCHexColor(0x282828)
                                                   textFont:25*kUIScaleBasePlus];
        _titleLabel.text = @"欢迎登录/注册导购天眼";
    }
    return _titleLabel;
}

- (UIButton *)demoButton
{
    if (!_demoButton)
    {
        _demoButton = [Utilties creatButtonWithFrame:CGRectMake(40*kUIScaleBasePlus,CGRectGetMaxY(self.titleLabel.frame)+49.5*kUIScaleBasePlus,120*kUIScaleBasePlus,18.5*kUIScaleBasePlus)
                                            textAligment:UIControlContentHorizontalAlignmentCenter
                                                    text:@"新用户体验"
                                                textClor:LCHexColor(0xFF7A17)
                                               buttonBGC:[UIColor clearColor]
                                                textFont:20*kUIScaleBasePlus
                                                  target:self
                                                  method:@selector(segmentClick:)];
        [_demoButton.titleLabel setFont:[UIFont fontWithName:@"Helvetica-Bold" size:20*kUIScaleBasePlus]];
        _demoButton.tag = 1;
        
    }
    return _demoButton;
}

- (UIView*)demoLineView
{
    if (!_demoLineView)
    {
        _demoLineView = [[UIView alloc]initWithFrame:CGRectMake(40*kUIScaleBasePlus,CGRectGetMaxY(self.demoButton.frame)+6.5*kUIScaleBasePlus,120*kUIScaleBasePlus, 2*kUIScaleBasePlus)];
        _demoLineView.backgroundColor = LCHexColor(0xFF7A17);
    }
    return _demoLineView;
}

- (UIButton *)businessButton
{
    if (!_businessButton)
    {
        _businessButton = [Utilties creatButtonWithFrame:CGRectMake(CGRectGetMaxX(self.demoButton.frame)+42.5*kUIScaleBasePlus,CGRectGetMaxY(self.titleLabel.frame)+49.5*kUIScaleBasePlus,130*kUIScaleBasePlus,18.5*kUIScaleBasePlus)
                                            textAligment:UIControlContentHorizontalAlignmentCenter
                                                    text:@"登入我的企业"
                                                textClor:LCHexColor(0x282828)
                                               buttonBGC:[UIColor clearColor]
                                                textFont:20*kUIScaleBasePlus
                                                  target:self
                                                  method:@selector(segmentClick:)];
        _businessButton.tag = 2;
        
    }
    return _businessButton;
}

- (UIView*)businessLineView
{
    if (!_businessLineView)
    {
        _businessLineView = [[UIView alloc]initWithFrame:CGRectMake(CGRectGetMaxX(self.demoButton.frame)+42.5*kUIScaleBasePlus,CGRectGetMaxY(self.businessButton.frame)+6.5*kUIScaleBasePlus,130*kUIScaleBasePlus, 2*kUIScaleBasePlus)];
        _businessLineView.backgroundColor = LCHexColor(0xFF7A17);
        _businessLineView.hidden = YES;
    }
    return _businessLineView;
}


- (DemoView *)demoView
{
    if (!_demoView)
    {
        _demoView = [[DemoView alloc]initWithFrame:CGRectMake(0,CGRectGetMaxY(self.demoLineView.frame)+40*kUIScaleBasePlus,SCREEN_WIDTH,250*kUIScaleBasePlus)];
        WeakSelf(self)
        _demoView.changeViewBlock = ^(NSString *phoneNum, NSString *code) {
            weakSelf.phoneDemoCode = code;
            weakSelf.phoneNum = phoneNum;
            [weakSelf login];
        };
        
        _demoView.loginFieldBlock = ^(LoginModel *model) {
            [weakSelf addSubview:weakSelf.loginFailedView];
            weakSelf.loginFailedView.model = model;
        };
    }
    return _demoView;
}

- (BussinessView *)bussinessView
{
    if (!_bussinessView)
    {
        _bussinessView = [[BussinessView alloc]initWithFrame:CGRectMake(SCREEN_WIDTH,CGRectGetMaxY(self.demoLineView.frame)+40*kUIScaleBasePlus,SCREEN_WIDTH,300*kUIScaleBasePlus)];
        
        WeakSelf(self)
        _bussinessView.getCompanyStrBlock = ^(NSString *phoneNum, NSString *code, NSInteger segmentNum) {
            weakSelf.phoneNum = phoneNum;
            weakSelf.phoneCode = code;
            weakSelf.segmentNum = segmentNum;
            [weakSelf login];
        };
        
        _bussinessView.getPhoneAndCipherBlock = ^(NSString *phoneNum, NSString *phoneCipher, NSInteger segmentNum) {
            weakSelf.phoneNum = phoneNum;
            weakSelf.phoneCipher = phoneCipher;
            weakSelf.segmentNum = segmentNum;
            [weakSelf login];
        };
        
        _bussinessView.loginFieldBlock = ^(LoginModel *model) {
            [weakSelf addSubview:weakSelf.loginFailedView];
             weakSelf.loginFailedView.model = model;
        };
    }
    return _bussinessView;
}

- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self)
    {
        self.segmentNum = 1;
        
        [self addSubview:self.titleLabel];
        [self addSubview:self.demoButton];
        [self addSubview:self.demoLineView];
        [self addSubview:self.businessButton];
        [self addSubview:self.businessLineView];
        [self addSubview:self.demoView];
        [self addSubview:self.bussinessView];
    }
    return self;
}

#pragma mark - segmentClick
- (void)segmentClick:(UIButton *)sender
{
    
    self.segmentNum = sender.tag;
    
    if (sender.tag == 1)
      {
          self.demoLineView.hidden = NO;
          self.businessLineView.hidden = YES;

          [self.demoButton.titleLabel setFont:[UIFont fontWithName:@"Helvetica-Bold" size:20*kUIScaleBasePlus]];
          [self.businessButton.titleLabel setFont:[UIFont systemFontOfSize:20*kUIScaleBasePlus]];
          
          [self.demoButton setTitleColor:LCHexColor(0xFF7A17) forState:UIControlStateNormal];
          [self.businessButton setTitleColor:LCHexColor(0x282828) forState:UIControlStateNormal];
          
          [UIView animateWithDuration:0.2 animations:^{
              [self.demoView setX:0];
              [self.bussinessView setX:SCREEN_WIDTH];
          } completion:^(BOOL finished) {
                       
          }];
     }
      else if(sender.tag == 2)
      {
          self.demoLineView.hidden = YES;
          self.businessLineView.hidden = NO;

          [self.demoButton.titleLabel setFont:[UIFont systemFontOfSize:20*kUIScaleBasePlus]];
          [self.businessButton.titleLabel setFont:[UIFont fontWithName:@"Helvetica-Bold" size:20*kUIScaleBasePlus]];
                 
          [self.demoButton setTitleColor:LCHexColor(0x282828) forState:UIControlStateNormal];
          [self.businessButton setTitleColor:LCHexColor(0xFF7A17) forState:UIControlStateNormal];

          [UIView animateWithDuration:0.2 animations:^{
                 [self.demoView setX:-SCREEN_WIDTH];
                 [self.bussinessView setX:0];
             } completion:^(BOOL finished) {
              
             }];
      }
}

#pragma mark - Method

- (void)login
{
    [self endEditing:YES];
    
    if (self.segmentNum == 1)
    {
        
        if (![self.phoneDemoCode isValidString])
          {
              DISMISS_SVP(0.5)
              [SVProgressHUD showWithStatus:@"请输入正确的验证码"];
              return;
          }
        
        NSDictionary *pramaters = @{
                                           @"phoneNum" : self.phoneNum,
                                           @"code" : self.phoneDemoCode
                                   };
               
        WeakSelf(self)
        [SVProgressHUD showWithStatus:nil];
        [infoManager getDemoLoginRequestWithParamers:pramaters sucess:^(id  _Nonnull acceptData) {
            NSNumber *code = acceptData[@"code"];
            if (code.integerValue == 400)
            {
                DISMISS_SVP(1.0f);

                LoginModel *model = [[LoginModel alloc]init];
                model.message = acceptData[@"message"];
                model.image = @"denglushibai";
                model.title = @"登录失败";
                [weakSelf addSubview:weakSelf.loginFailedView];
                weakSelf.loginFailedView.model = model;
            }
            else
            {
                current_User.username = self.phoneNum;
                [[NSOperationQueue mainQueue] addOperationWithBlock:^{
                [current_User savaSessionSucess:^{
                                                                             
                } fail:^(NSError *error) {
                                                                                
                }];
                }];
                                                                        
                DISMISS_SVP(1.0f);
                LCUserDefaultsSet(current_User.username,kLoginUser);
                                                                        
                                                                        
                if (current_User.missingIndestry.integerValue == 1)
                {
                    if (self.changeToIndustryViewBlock)
                    {
                        self.changeToIndustryViewBlock();
                    }
                                                                         
                }
                else
                {
                                                                            
                    if ([self.type isEqualToString:@"0"])
                    {
                        UIViewController *topRootViewController = [UIApplication sharedApplication].keyWindow.rootViewController;
                        while (topRootViewController.presentedViewController)
                        {
                            topRootViewController = topRootViewController.presentedViewController;
                        }
                                                                            
                            [topRootViewController dismissViewControllerAnimated:YES completion:^{
                                                                                    
                            }];
                        }
                        else
                        {
                                                                                
                            AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
                                                                                
                            kKeyWindow.rootViewController = appDelegate.vc;
                            [kKeyWindow.window makeKeyAndVisible];
                            [appDelegate gotoHome];
                            
                        }
                    
                        [[NSNotificationCenter defaultCenter] postNotificationName:@"RefreshLabel" object:nil userInfo:nil];

                        NSString *str = current_User.detail;
                        if ([str isValidString])
                            {
                                NSDictionary *dic = @{@"detail":str,@"isNew":@"0"};
                                [[NSNotificationCenter defaultCenter] postNotificationName:@"UPDATEVERSON" object:nil userInfo:dic];
                            }
                        }
                    }
                                                        
        } fail:^(NSError * _Nullable error) {
            
        }];
    }
    else if(self.segmentNum == 2)
    {
        
        if (![self.phoneCode isValidString])
          {
              DISMISS_SVP(0.5)
              [SVProgressHUD showWithStatus:@"请输入正确的验证码"];
              return;
          }
        
        NSDictionary *pramaters = @{
                                           @"phoneNum" : self.phoneNum,
                                           @"code" : self.phoneCode
                                           };
               
               WeakSelf(self)
               [SVProgressHUD showWithStatus:nil];
               [infoManager getLoginRequestWithParamers:pramaters sucess:^{
                   
                   current_User.username = weakSelf.phoneNum;
                   [[NSOperationQueue mainQueue] addOperationWithBlock:^{
                       [current_User savaSessionSucess:^{
                        
                       } fail:^(NSError *error) {
                           
                       }];
                   }];
                   
                   DISMISS_SVP(1.0f);
                   LCUserDefaultsSet(current_User.username,kLoginUser);
                   
                   
                   if (current_User.missingIndestry.integerValue == 1)
                   {
                       if (weakSelf.changeToIndustryViewBlock)
                       {
                           weakSelf.changeToIndustryViewBlock();
                       }
                    
                   }
                   else
                   {
                       
                       if ([weakSelf.type isEqualToString:@"0"])
                       {
                           UIViewController *topRootViewController = [UIApplication sharedApplication].keyWindow.rootViewController;
                           while (topRootViewController.presentedViewController)
                           {
                               topRootViewController = topRootViewController.presentedViewController;
                           }
                           
                           [topRootViewController dismissViewControllerAnimated:YES completion:^{
                               
                           }];
                       }
                       else
                       {
                           
                           AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
                           
                           kKeyWindow.rootViewController = appDelegate.vc;
                           [kKeyWindow.window makeKeyAndVisible];
                           [appDelegate gotoHome];
                       }
                       
                       [[NSNotificationCenter defaultCenter] postNotificationName:@"RefreshLabel" object:nil userInfo:nil];


                       NSString *str = current_User.detail;
                       if ([str isValidString])
                        {
                            NSDictionary *dic = @{@"detail":str,@"isNew":@"0"};
                            [[NSNotificationCenter defaultCenter] postNotificationName:@"UPDATEVERSON" object:nil userInfo:dic];
                        }
                   }
                   
               } fail:^(NSError *error) {
                   DISMISS_SVP(1.0f);
               }];
    }
    else
    {
    if (![self.phoneCipher isValidString])
        {
            DISMISS_SVP(0.5)
            [SVProgressHUD showWithStatus:@"请输入正确的密码"];
            return;
        }
        
        NSDictionary *pramaters = @{
                                        @"phoneNum" : self.phoneNum,
                                        @"password" : self.phoneCipher
                                    };
                      
                      WeakSelf(self)
                      [SVProgressHUD showWithStatus:nil];
        [infoManager getLoginWithPassWordRequestWithParamers:pramaters sucess:^(id  _Nonnull acceptData) {
            NSNumber *code = acceptData[@"code"];
                    if (code.integerValue == 400)
                       {
                           DISMISS_SVP(1.0f);

                           LoginModel *model = [[LoginModel alloc]init];
                           model.message = acceptData[@"message"];
                           model.image = @"denglushibai";
                           model.title = @"登录失败";
                           [weakSelf addSubview:weakSelf.loginFailedView];
                           weakSelf.loginFailedView.model = model;
                       }
                       else
                       {
                           current_User.username = self.phoneNum;
                           [[NSOperationQueue mainQueue] addOperationWithBlock:^{
                               [current_User savaSessionSucess:^{
                                
                               } fail:^(NSError *error) {
                                   
                               }];
                           }];
                           
                           DISMISS_SVP(1.0f);
                           LCUserDefaultsSet(current_User.username,kLoginUser);
                           
                           
                           if (current_User.missingIndestry.integerValue == 1)
                           {
                               if (weakSelf.changeToIndustryViewBlock)
                               {
                                   weakSelf.changeToIndustryViewBlock();
                               }
                            
                           }
                           else
                           {
                               
                               if ([weakSelf.type isEqualToString:@"0"])
                               {
                                   UIViewController *topRootViewController = [UIApplication sharedApplication].keyWindow.rootViewController;
                                   while (topRootViewController.presentedViewController)
                                   {
                                       topRootViewController = topRootViewController.presentedViewController;
                                   }
                                   
                                   [topRootViewController dismissViewControllerAnimated:YES completion:^{
                                       
                                   }];
                               }
                               else
                               {
                                   
                                   AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
                                   
                                   kKeyWindow.rootViewController = appDelegate.vc;
                                   [kKeyWindow.window makeKeyAndVisible];
                                   
                                   [appDelegate gotoHome];
                               }
                               
                               [[NSNotificationCenter defaultCenter] postNotificationName:@"RefreshLabel" object:nil userInfo:nil];

                               NSString *str = current_User.detail;
                               if ([str isValidString])
                                {
                                    NSDictionary *dic = @{@"detail":str,@"isNew":@"0"};
                                    [[NSNotificationCenter defaultCenter] postNotificationName:@"UPDATEVERSON" object:nil userInfo:dic];
                                }
                           }
                       }
        } fail:^(NSError * _Nullable error) {
            
        }];
    }
}


/**
 *  获取登录信type
*/
- (void)getType:(NSString *)type
{
    self.type = type;
}
@end
